<template>
  <a-card :bordered="false">
    <div class="table-operator" style="display: flex; justify-content: space-between;">
      <a-button v-if="hasPerm('ReturnTicket.Add')" type="primary" @click="SearchClick()">申请退票</a-button>
      <a-form layout="inline">
        <a-row>
          <a-col :md="24" :sm="24">

            <a-input
              style="width: 150px;"
              v-model="queryParam.keyword"
              placeholder="请输入购货方名称"
              @keydown.enter="getDataList" />
            <a-select
              allowClear
              v-model="queryParam.InvoiceState"
              placeholder="退票状态"
              style="width: 120px;margin-left: 10px;">
              <a-select-option v-for="i in invoiceStateSelectOptions" :key="i.value" :value="i.value">
                {{ i.label }}
              </a-select-option>
            </a-select>
            <a-select
              allowClear
              v-model="queryParam.ReturnCheckStatus"
              placeholder="审核状态"
              style="width: 120px;margin-left: 10px;">
              <a-select-option v-for="i in RefundStatusSelectOptions" :key="i.value" :value="i.value">
                {{ i.label }}
              </a-select-option>
            </a-select>
            <a-select
              allowClear
              style="width: 100px;margin-left: 8px;"
              v-model="selectTime"
              @change="changeTime"
              name="radioGroup"
              :default-value="0">
              <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
                {{ i }}
              </a-select-option>
            </a-select>
            <a-range-picker
              style="margin-left: 8px;width: 220px;"
              :disabled="timeDisabled"
              valueFormat="YYYY-MM-DD"
              v-model="time" />
            <a-button
              style="margin-left: 8px"
              type="primary"
              @click="() => {
                this.pagination.current = 1
                this.getDataList()
              }
              ">查询
            </a-button>
            <a-button @click="repossess">重置
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-page-search-wrapper">
      <!-- <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select allowClear v-model="queryParam.condition">
                <a-select-option key="TicketbuyerName">客户</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.keyword" placeholder="关键字" @keydown.enter="getDataList" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="查询时间">
              <a-range-picker v-model="time" />
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="24">
            <a-select default-value="一个月" style="width: 80px" @change="handleChange">
              <a-select-option v-for="i in ['一个月','三个月','六个月']" :key="i">
                {{ i }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-button type="primary" @click="() => {
              this.pagination.current = 1
              this.getDataList()
            }
              ">查询
            </a-button>
            <a-button style="margin-left: 8px" @click="repossess">重置
            </a-button>
          </a-col>
        </a-row>
      </a-form> -->

    </div>
    <a-table
      ref="table"
      :scroll="{ y: 'calc(100vh - 330px)' }"
      :columns="columns"
      :rowKey="(row) => row.Id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small">
      <template slot="Amountincludingtax" slot-scope="text, record">
        {{ record.Amountincludingtax }}
      </template>
      <template slot="RefundStatus" slot-scope="text, record">
        <a-tag
          v-if="text == '1' && record.InvoiceState != '20' && record.InvoiceState != '30'"
          color="#87d068">已申请</a-tag>
        <a-tag
          v-if="text == '2' && record.InvoiceState != '20' && record.InvoiceState != '30'"
          color="#2db7f5">审核通过</a-tag>
        <a-tag v-if="text == '3' && record.InvoiceState != '20' && record.InvoiceState != '30'" color="cyan">驳回</a-tag>
        <a-tag v-if="record.InvoiceState == '20' || record.InvoiceState == '30'" color="pink">已完成</a-tag>
      </template>
      <template slot="InvoiceState" slot-scope="text, record">
        <!-- <a-tag v-if="text=='10'" color="#87d068">已申请</a-tag> -->
        <a-tag v-if="text == '20'" color="#2db7f5">已被红冲</a-tag>
        <a-tag v-if="text == '30'" color="red">已被作废</a-tag>
        <a-tag v-if="text == '40'" color="cyan">失控</a-tag>
        <a-tag v-if="text == '50'" color="cyan">异常</a-tag>
        <a-tag v-if="text == '60'" color="cyan">待红冲</a-tag>
        <a-tag v-if="text == '70'" color="cyan">待作废</a-tag>
        <!-- <a-tag v-else></a-tag> -->
      </template>
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime, 'YYYY-MM-DD') }}</span>
      <template slot="State" slot-scope="text, record">
        {{ record.State === 'Running'
          ? '审批中'
          : record.State === 'Finished'
            ? '已完成'
            : record.State === 'Canceled'
              ? '已取消'
              : record.State === 'Exceptional'
                ? '异常'
                : record.State === 'Suspended'
                  ? '已停止'
                  : record.State === 'Timeout'
                    ? '已超时'
                    : '审批中' }}
      </template>
      <span slot="Invoicenumber" slot-scope="Invoicenumber">
        <a-tooltip placement="topLeft">
          <template #title>
            <span>{{ ShowNumber(Invoicenumber) }}</span>
          </template>
          <div v-html="ShowNumber(Invoicenumber, true)"></div>
        </a-tooltip>
      </span>
      <span slot="Invoicenumber1" slot-scope="Invoicenumber1">
        <a-tooltip placement="topLeft">
          <template #title>
            <span>{{ ShowNumber1(Invoicenumber1) }}</span>
          </template>
          <div v-html="ShowNumber1(Invoicenumber1, true)"></div>
        </a-tooltip>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <!-- <a v-if="hasPerm('Base_District.Edit')" @click="handleEdit(record.Id)">编辑</a> -->
          <!-- <a-divider v-if="hasPerm('Base_District.Edit') && hasPerm('Base_District.Delete')" type="vertical" /> -->
          <a v-if="hasPerm('ReturnTicket.view')" @click="handleDetails(record)">详情</a>
          <a
            v-if="hasPerm('ReturnTicket.Apply') && record.RefundStatus == 1"
            @click="handleApply(record, '2', '通过')"
            style="margin-left: 10px;">通过</a>
          <a
            v-if="hasPerm('ReturnTicket.Reject') && record.RefundStatus == 1"
            @click="handleApply(record, '3', '驳回')"
            style="margin-left: 10px;">驳回</a>
          <a
            v-if="hasPerm('ReturnTicket.Cancel') && record.RefundStatus == 1"
            @click="handleApply(record, '0', '作废')"
            style="margin-left: 10px;">作废</a>
          <!-- <a-divider v-if="hasPerm('Base_District.Edit') && hasPerm('Base_District.Delete')" type="vertical" /> -->
          <!-- <a v-if="record.InstanceId" @click="handleHistory(record.NewInstanceId)">审批历史</a> -->
          <!-- <a-divider v-if="hasPerm('Base_District.Edit') && hasPerm('Base_District.Delete')" type="vertical" />
                    <a v-if="record.InstanceId" @click="handleHistory(record.InstanceId)">审批历史</a>
                    <a-divider v-if="record.State == 'Finished'" type="vertical" />
                    <a v-if="record.State == 'Finished'" @click="returnTicket(record)">退票</a> -->
        </template>
      </span>
    </a-table>
    <a-drawer
      title="审批历史"
      width="30%"
      :confirmLoading="loading"
      placement="right"
      :visible="visiblees"
      @close="() => {
        this.visiblees = false
      }
      "
      :body-style="{ paddingBottom: '80px' }">
      <a-steps progress-dot :current="steps.length - 1" direction="vertical">
        <a-step v-for="(item, index) in steps" :key="index" :title="item.Title">
          <div style="width:300px" slot="description">
            <div>
              <span>{{ item.UserName }}</span>
              <a-tag :color="item.color">
                {{ item.type }} {{ item.State == 'Finished' ? item.FinishTime : '' }}
              </a-tag>
            </div>
            <span v-show="item.State != 'ToDo' && item.Comment">{{ item.Comment }}</span>
            <p>{{ item.StartTime }}</p>
          </div>
        </a-step>
      </a-steps>
    </a-drawer>
    <a-drawer
      title="申请退票"
      width="70%"
      :confirmLoading="loading"
      placement="right"
      :visible="visible"
      @close="close"
      :body-style="{ paddingBottom: '80px' }">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <!-- <a-col :md="4" :sm="24">
                            <a-form-item label="查询类别">
                                <a-select allowClear v-model="queryParam.condition">
                                    <a-select-option key="Name">申请号</a-select-option>
                                    <a-select-option key="ParentId">客户</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col> -->
            <a-col :md="5" :sm="24">
              <div style="display: flex;">
                <a-form-item label="发票号">
                  <a-input v-model="InvoiceCode" placeholder="发票号" @keydown.enter="addSerach" style="width: 100%;" />
                </a-form-item>
              </div>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item style="width: 300px;" label="客户名称">
                <div style="display: flex;">
                  <a-input :disabled="true" v-model="Name.cCusName" placeholder="客户名称" @keydown.enter="getDataList" />
                  <a-button type="primary" @click="handleOpenChoose">
                    <a-icon type="search" />
                  </a-button>
                </div>
              </a-form-item>
            </a-col>
            <!--
            <a-col style="margin-top: 5px; " :md="1" :sm="24">
            </a-col>
            <a-col :md="3" :sm="24">

            </a-col> -->
            <!-- @click="() => {
                  this.pagination2.current = 1
                  this.getDataList()
                }" -->
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="addSerach">查询
              </a-button>
              <a-button style="margin-left: 8px" @click="reset">重置
              </a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- //申请退票表格 -->
      <!-- :pagination="pagination2" -->
      <a-table
        ref="table"
        :scroll="{ y: tableHeight }"
        :columns="columns1"
        :rowKey="(row) => row.Id"
        :dataSource="returnData"
        :loading="Addloading"
        @change="handleTableChange4"
        :pagination="pagination4"
        :rowSelection="{ selectedRowKeys: selectedRowKeys1, onChange: onSelectChange1, type: 'radio', getCheckboxProps: getAddCheckboxProps }"
        :bordered="true"
        size="small">
        <template slot="Amountincludingtax" slot-scope="text, record">
          {{ record.Amountincludingtax }}
        </template>
        <!-- <template slot="InvoiceState" slot-scope="text, record">
          <a-tag v-if="text == '10'" color="#87d068">已开票</a-tag>
          <a-tag v-if="text == '20'" color="#2db7f5">已红冲</a-tag>
          <a-tag v-if="text == '30'" color="red">已作废</a-tag>
          <a-tag v-if="text == '40'" color="cyan">失控</a-tag>
          <a-tag v-if="text == '50'" color="cyan">异常</a-tag>
          <a-tag v-if="text == '60'" color="cyan">待红冲</a-tag>
          <a-tag v-if="text == '70'" color="cyan">待作废</a-tag>
          <a-tag v-if="text == '0'" color="cyan">未返回状态</a-tag>
        </template> -->
        <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime, 'YYYY-MM-DD') }}</span>

        <span slot="Invoicenumber" slot-scope="Invoicenumber">
          <a-tooltip placement="topLeft">
            <template #title>
              <span>{{ ShowNumber(Invoicenumber) }}</span>
            </template>
            <div v-html="ShowNumber(Invoicenumber, true)"></div>
          </a-tooltip>
        </span>

        <template slot="State" slot-scope="text, record">
          {{ record.State === 'Running'
            ? '审批中'
            : record.State === 'Finished'
              ? '已完成'
              : record.State === 'Canceled'
                ? '已取消'
                : record.State === 'Exceptional'
                  ? '异常'
                  : record.State === 'Suspended'
                    ? '已停止'
                    : record.State === 'Timeout'
                      ? '已超时'
                      : '审批中' }}
        </template>
      </a-table>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
        <a-button
          :style="{ marginRight: '8px' }"
          @click="() => {
            this.visible = false
          }
          ">取消</a-button>

        <a-button :disabled="selectedRowKeys1.length <= 0" type="primary" @click="handleSubmit">确定</a-button>

      </div>
    </a-drawer>
    <OutboundDetails ref="OutboundDetails" />
    <a-modal
      title="选择客户名称"
      width="70%"
      :visible="visibleName"
      @cancel="() => {
        this.visibleName = false;
      }"
      @ok="chooseNameOK">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="10">
            <a-col :md="7" :sm="24">
              <a-form-item label="查询类别">
                <a-select allowClear v-model="chooseParam.condition">
                  <a-select-option key="cCusCode">客户编号</a-select-option>
                  <a-select-option key="cCusName">客户名称</a-select-option>
                  <a-select-option key="cCusAddres">客户地址</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-input v-model="chooseParam.keyword" placeholder="关键字" @keydown.enter="getDataList" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-button
                type="primary"
                @click="() => {
                  this.pagination3.current = 1
                  this.getChooseData()
                }
                ">查询
              </a-button>
              <a-button
                style="margin-left: 8px"
                @click="; (chooseParam = { condition: 'cCusName' }); getChooseData()">重置
              </a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-table
        ref="table"
        :scroll="{ y: tableHeight }"
        :columns="columsName"
        :rowKey="(row) => row.Id"
        :dataSource="chooseData"
        :pagination="pagination3"
        :loading="loadingChoose"
        @change="handleTableChange3"
        :rowSelection="{ selectedRowKeys: selectedNameRowKeys, onChange: onSelectChangeName, type: 'radio' }"
        :bordered="true"
        size="small">
        <span slot="Invoicenumber" slot-scope="Invoicenumber">
          <a-tooltip placement="topLeft">
            <template #title>
              <span>{{ ShowNumber(Invoicenumber) }}</span>
            </template>
            <div v-html="ShowNumber(Invoicenumber, true)"></div>
          </a-tooltip>
        </span>
        
        <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime, 'YYYY-MM-DD') }}</span>
      </a-table>
    </a-modal>
    <EditForm ref="EditForm" :parentObj="{ ...this }" />

  </a-card>
</template>

<script>
import moment from 'moment'
import OutboundDetails from '../InvoiceApplication/OutboundDetails'
import EditForm from './EditForm'
import { invoiceNumberAbbr } from '@/utils/Tools.js'

const columns = [

  { title: '申请码', dataIndex: 'Code', ellipsis: true },
  { title: '红字发票号', dataIndex: 'Invoicenumber', scopedSlots: { customRender: 'Invoicenumber' } },
  { title: '蓝字发票号', dataIndex: 'Invoicenumber1', scopedSlots: { customRender: 'Invoicenumber1' } },
  { title: '购货方', dataIndex: 'TicketbuyerName', width: '480px' },
  // { title: '名称', dataIndex: 'Accbank',ellipsis: true, },
  // { title: '账户', dataIndex: 'BankAccount',ellipsis: true, },
  { title: '含税金额(小写)', dataIndex: 'Amountincludingtax', align: 'right', scopedSlots: { customRender: 'Amountincludingtax' }, width: '120px' },
  // { title: '含税金额(大写)', dataIndex: 'Includingtaxinwords' },
  // { title: '电话', dataIndex: 'PayeeUserPhone' },
  // { title: '地址', dataIndex: 'PayeeUserAddres' },
  { title: '退票人', dataIndex: 'Refunder',width:'90px'  },
  {
    title: '退票时间',
    dataIndex: 'RefundDate',
    customRender: (value) => {
      return value.substring(0, 10)
    },
    width:'90px'
  },
  // { title: '备注', dataIndex: 'Memo' },
  { title: '退票状态', dataIndex: 'InvoiceState', scopedSlots: { customRender: 'InvoiceState' }, align: 'center',width:'90px' },
  { title: '审核状态', dataIndex: 'RefundStatus', scopedSlots: { customRender: 'RefundStatus' }, align: 'center',width:'90px'  },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, width: '160px', align: 'center' }
]
const columns1 = [
  { title: '日期', dataIndex: 'CreateTime', scopedSlots: { customRender: 'CreateTime' } },
  { title: '发票号码', dataIndex: 'Invoicenumber', scopedSlots: { customRender: 'Invoicenumber' } },
  { title: '发票代码', dataIndex: 'Invoicecode' },
  // { title: '税号', dataIndex: 'TaxRegcode',  ellipsis: true,},
  // { title: '名称', dataIndex: 'Accbank',ellipsis: true, },
  // { title: '账户', dataIndex: 'BankAccount',ellipsis: true, },
  { title: '购货方', dataIndex: 'TicketbuyerName', align: 'left', width: '200px' },
  // { title: '含税金额(大写)', dataIndex: 'Includingtaxinwords' },
  // { title: '金额', dataIndex: 'InvoiceAmount', align: 'right' },
  { title: '含税金额(小写)', dataIndex: 'Amountincludingtax', align: 'right', scopedSlots: { customRender: 'Amountincludingtax' }, width: '120px' },
  // { title: '状态', dataIndex: 'InvoiceState', scopedSlots: { customRender: 'InvoiceState' } },

  { title: '备注', dataIndex: 'Remark' }
]
const columsName = [
  { title: '客户编号', dataIndex: 'cCusCode', width: '30%' },
  { title: '客户名称', dataIndex: 'cCusName', width: '30%' },
  { title: '客户地址', dataIndex: 'cCusAddres', width: '30%' }
]
export default {
  components: {
    OutboundDetails,
    EditForm
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHeight = this.getTableHeight(true) + 24
      this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
      this.getDataList()
      this.getChooseData()
    })
  },
  data () {
    return {
      Addloading: false,
      InvoiceCode: '', // 申请退票发票号
      tableHeight: 570, // 表格高度
      data: [],
      visible: false,
      columsName,
      timeDisabled: true,
      returnData: [], // 申请退票数据
      pagination: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      pagination2: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      pagination3: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      pagination4: {
        current: 1,
        pageSize: 20,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      filters: {},
      selectedRowKeys1: [],
      sorter: { field: 'RefundDate', order: 'desc' },
      loading: false,
      loadingChoose: false,
      columns,
      entity: {},
      queryParam: {
        condition: 'TicketbuyerName'
      },
      selectedNameRowKeys: [],
      selectedNameRowKeysData: [],
      selectedRowKeys: [],
      steps: [],
      columns1,
      details: false,
      visiblees: false,
      InvoicenumberStart: '', // 发票号开始
      InvoicenumberEnd: '', // 发票号结束
      visibleName: false, // 选择客户名称弹框
      chooseParam: {
        condition: 'cCusName'
      },
      chooseData: [], // 客户名称数据
      Name: {}, // 客户名称选择
      time: [],
      selectTime: 0,
      invoiceStateSelectOptions: [
        {
          value: '20',
          label: '已被红冲'
        },
        {
          value: '30',
          label: '已被作废'
        },
        {
          value: '40',
          label: '失控'
        },
        {
          value: '50',
          label: '异常'
        },
        {
          value: '60',
          label: '待红冲'
        },
        {
          value: '70',
          label: '待作废'
        }
      ],
      RefundStatusSelectOptions: [
        {
          value: '1',
          label: '已申请'
        },
        {
          value: '2',
          label: '审核通过'
        },
        {
          value: '3',
          label: '驳回'
        }
      ]
    }
  },
  methods: {
    ReplaceNull (str) {
      return str.replace(/null/g, '')
    },
    handleApply (row, type, title) {
      this.$confirm(`确认${title}吗?`, '审批', {
        confirmButtonText: '通过',
        cancelButtonText: '取消',
        type: 'warning'

      }).then(() => {
        this.$http.post(`/InvoiceManagement/Inv_InvoiceApplyMain/SetInvoiceState?id=${row.Id}&Type=${type}`).then(res => {
          if (res.Success) {
            this.$message.success(title + '成功')
            this.getDataList()
          } else {
            this.$message.success(res.Msg)
          }
        })
      })
    },
    getAddCheckboxProps (row) {
      let flag
      if (row.RefundStatus == '1' || row.RefundStatus == '2' || row.RefundStatus == '3') {
        flag = true
      } else {
        flag = false
      }
      return {
        props: {
          disabled: flag
        }
      }
    },
    addSerach () {
      this.pagination3.current = 1
      this.getAddDataList()
    },
    getAddDataList () {
      this.Addloading = true
      this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetRefundDataList', {
          PageIndex: this.pagination4.current,
          PageRows: this.pagination4.pageSize,
          // SortField: this.sorter.field || 'Id',
          // SortType: this.sorter.order,
          Search: {
            InvoiceCode: this.InvoiceCode,
            Customer: this.Name.cCusName
          }
        }).then(res => {
          this.Addloading = false
          if (res.Success) {
            res.Data.forEach(item => {
              item.Amountincludingtax = this.$options.filters.NumberFormats(item.Amountincludingtax)
              item.Remark = item.Remark ? this.ReplaceNull(item.Remark) : ''
            })
            this.returnData = res.Data
          } else {
            this.returnData = []
            this.$message.error(res.Msg)
          }
        })
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.getDataList()
    },
    handleTableChange2 (pagination, filters, sorter) {
      this.pagination2 = { ...pagination }
      this.filters = { ...filters }
      this.getReturnData()
    },
    handleTableChange3 (pagination, filters, sorter) {
      this.pagination3 = { ...pagination }
      this.filters = { ...filters }
      this.getChooseData()
    },
    handleTableChange4 (pagination, filters, sorter) {
      this.pagination4 = { ...pagination }
      this.filters = { ...filters }
      this.getAddDataList()
    },
    repossess () {
      this.queryParam = { condition: 'TicketbuyerName' }
      this.changeTime(0)
      this.getDataList()
    },
    // 关闭弹框
    close () {
      this.visible = false
      this.Name = {}
      this.InvoicenumberStart = ''
      this.InvoicenumberEnd = ''
    },
    changeTime (e) {
      this.timeDisabled = true
      this.selectTime = e
      this.time = []
      switch (e) {
        case 0:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 1:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 2:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 3:
          this.timeDisabled = false
          break
      }
    },
    reset () {
      this.InvoiceCode = ''
      // this.chooseParam = { condition: 'cCusName' }
      // this.InvoicenumberStart = ''
      // this.InvoicenumberEnd = ''
      this.Name = {}
      // this.getReturnData()
    },
    getDataList () {
      this.selectedRowKeys = []
      const this_ = this
      this.loading = true
      this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetReturnDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: {
            ...this.queryParam,
            StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '',
            EndTime: this.time[1] ? this.timeFormat(this.time[1]) : '',
            Refundstatus: 9

          },
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          this.data.forEach(item => {
            item.Amountincludingtax = this_.$options.filters.NumberFormats(item.Amountincludingtax)
            item.Invoicenumber1=item.Invoicenumber
          })
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
      // this.$http
      //   .post('/InvoiceManagement/Inv_ReturnTicketMain/GetDataList', {
      //     PageIndex: this.pagination.current,
      //     PageRows: this.pagination.pageSize,
      //     SortField: this.sorter.field || 'Id',
      //     SortType: this.sorter.order,
      //     Search: { ...this.queryParam, StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '', EndTime: this.time[1] ? this.timeFormat(this.time[1]) : '' },
      //     ...this.filters
      //   })
      //   .then(resJson => {
      //     this.loading = false
      //     this.data = resJson.Data
      //     this.data.forEach(item => {
      //       item.RefundTime = item.RefundTime.slice(0, 10)
      //       item.Amountincludingtax = this_.$options.filters.NumberFormats(item.Amountincludingtax)
      //     })
      //     if (this.data) {
      //       const pagination = { ...this.pagination }
      //       pagination.total = resJson.Total
      //       this.pagination = pagination
      //     }
      //   })
    },
    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    },
    // 申请退票数据
    getReturnData () {
      // if (!this.Name.Id) {
      //   this.$message.warning('请选择客户名称')
      //   return;
      // }
      this.$http
        .post('/InvoiceManagement/Inv_Invoicing/GetRefundList', {
          PageIndex: this.pagination2.current,
          PageRows: this.pagination2.pageSize,
          SortField: 'Id',
          SortType: this.sorter.order,
          Search: {
            // "State": "Finished",
            // "Isreturnticket": true,
            'NumberStart': this.InvoicenumberStart,
            'NumberEnd': this.InvoicenumberEnd,
            'CusId': this.Name.cCusName
          },
          ...this.filters
        })
        .then(resJson => {
          this.loading = false
          this.returnData = resJson.Data
          this.returnData.forEach(item => {
            item.InvoiceAmount = this.$options.filters.NumberFormats(item.InvoiceAmount)
          })
          if (this.data) {
            const pagination = { ...this.pagination2 }
            pagination.total = resJson.Total
            this.pagination2 = pagination
          }
        })
    },
    handleDetails (record) {
      this.$refs.OutboundDetails.openInfo(record)// 打开
      return
      const this_ = this
      this.$http.post('/InvoiceManagement/Inv_ReturnTicketMain/GetReturnTicketDetail?Id=' + id).then(res => {
        this_.$refs.OutboundDetails.handleDetails(res.Data, true)
      })
    },
    // 选择名字
    onSelectChangeName (s, ss) {
      this.selectedNameRowKeys = s
      this.selectedNameRowKeysData = ss
    },
    handleHistory (id) {
      this.visiblees = true
      const obj = {
        'Finished': {
          name: '已完成',
          color: '#87d068'
        },
        'ToDo': {
          name: '待办',
          color: 'purple'
        },
        'Waiting': {
          name: '等待',
          color: 'red'
        },
        'UnRead': {
          name: '未读',
          color: 'red'
        },
        'Canceled': {
          name: '取消',
          color: 'red'
        },
        'Draft': {
          name: '草稿',
          color: 'red'
        },
        'Timeout': {
          name: '超时',
          color: 'red'
        },
        'Skiped': {
          name: '已跳过',
          color: 'red'
        }
      }
      this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/Open?InstanceId' + '=' + id).then(res => {
        res.Data.forEach(item => {
          item.StartTime = item.StartTime.slice(0, -4)
          item.FinishTime = item.FinishTime.slice(0, -4)
          item.type = obj[item.State].name
          item.color = obj[item.State].color
        })
        this.steps = res.Data
      })
    },
    handleSubmit () {
      if (!this.selectedRowKeys1.length) {
        return this.$message.warning('请选择')
      }
      // this.$http
      //   .post('/InvoiceManagement/Inv_Invoicing/GetDataListByMoreCondition', {
      //     Search: [{ condition: 'ApplyId', Keyword: this.selectedRowKeys1[0] }]
      //   })
      //   .then(resJson => {
      //     resJson.Data.forEach(item => {
      //       item.CreateTime = item.CreateTime.slice(0, 10)
      //       item.InvoiceAmount = this.$options.filters.NumberFormats(item.InvoiceAmount)
      //       item.InvoiceTaxAmount = this.$options.filters.NumberFormats(item.InvoiceTaxAmount)
      //     })
      //     this.invoiceDetail = resJson.Data
      //   }).catch(err => {
      //     this.$message.error(err)
      //   })
      // let record = this.returnData.filter(item => item.Id == this.selectedRowKeys1[0])[0]
      // this.$refs.EditForm.openInfo(record, '编辑') // 打开

      this.$confirm('确认退票吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post(`/InvoiceManagement/Inv_InvoiceApplyMain/SetInvoiceState?id=${this.selectedRowKeys1[0]}&type=${1}`).then(res => {
          if (res.Success) {
            this.visible = false
            this.$message.success('申请成功')
            this.getDataList()
          } else {
            this.$message.success('申请失败')
          }
        })
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelectChange1 (selectedRowKeys) {
      this.selectedRowKeys1 = selectedRowKeys
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },

    SearchClick () {
      this.visible = true
      this.InvoiceCode = ''
      this.returnData = []
      // this.getReturnData()
      // this.$refs.SearchCusinfo.openForm(null, '选择开票客户')
    },
    // 选择客户名称
    handleOpenChoose () {
      this.chooseParam = { condition: 'cCusName' }
      this.selectedNameRowKeysData = []
      this.selectedNameRowKeys = []
      this.visibleName = true
      this.getChooseData()
    },
    // 退票
    returnTicket (record) {
      console.log(record)
    },
    // 选择名字
    chooseNameOK () {
      if (!this.selectedNameRowKeysData[0]) {
        this.$message.error('请选择客户名称')
        return
      }
      this.visibleName = false
      this.Name = this.selectedNameRowKeysData[0]
      console.log(this.Name)
    },
    getChooseData () {
      this.selectedRowKeys = []
      this.loadingChoose = true
      this.$http
        .post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition', {
          PageIndex: this.pagination3.current,
          PageRows: this.pagination3.pageSize,
          'SortField': 'Id',
          'SortType': 'desc',
          'Search': [{ 'Condition': this.chooseParam.condition, Keyword: this.chooseParam.keyword },
            { 'condition': 'cCusType', 'keyword': 1 }
            // { Condition: 'cCusName',  }
          ]
        })
        .then((resJson) => {
          this.loadingChoose = false
          this.chooseData = resJson.Data
          if (this.chooseData) {
            const pagination = { ...this.pagination3 }
            pagination.total = resJson.Total
            this.pagination3 = pagination
          }
        })
    },
    handleDelete (ids) {
      var thisObj = this
      // this.$confirm({
      //     title: '确认删除吗?',
      //     onOk() {
      //         return new Promise((resolve, reject) => {
      //             thisObj.$http.post('/Base_BasicData/Base_District/DeleteData', ids).then((resJson) => {
      //                 resolve()

      //                 if (resJson.Success) {
      //                     thisObj.$message.success('操作成功!')

      //                     thisObj.getDataList()
      //                 } else {
      //                     thisObj.$message.error(resJson.Msg)
      //                 }
      //             })
      //         })
      //     }
      // })
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        thisObj.$http
          .post('/Base_BasicData/Base_District/DeleteData', ids)
          .then(resJson => {
            // resolve()

            if (resJson.Success) {
              thisObj.$message.success('操作成功!')

              thisObj.getDataList()
            } else {
              thisObj.$message.error(resJson.Msg)
            }
          })
      })
    },
    ShowNumber (text, eclipse) {
      if (eclipse && text) {
        if (text.includes(',')) {
          const textarr = text.split(',')
          // return invoiceNumberAbbr(textarr[0]) + ',<br>' + invoiceNumberAbbr(textarr[1])
          return invoiceNumberAbbr(textarr[0])
        } else {
          return invoiceNumberAbbr(text)
        }
      }
      return text.split(',')[0]//text
    },
    ShowNumber1 (text, eclipse) {
      if (eclipse && text) {
        if (text.includes(',')) {
          const textarr = text.split(',')
          // return invoiceNumberAbbr(textarr[0]) + ',<br>' + invoiceNumberAbbr(textarr[1])
          return invoiceNumberAbbr(textarr[1])
        } else {
          return invoiceNumberAbbr(text)
        }
      }
      return text.split(',')[1]//text
    }
  }
}
</script>
<style scoped>
/deep/ .ant-steps-item-content {
  width: 300px;
}

.cancel {
  color: red;
}
/deep/ .ant-card-body {
  padding-bottom: 0;
}
</style>
